<?php
Class OrderController extends Controller{
	public function __construct(){
		$this->calledClass(get_class($this));
	}
	public function DisplayAdminPackageOrder(){
		$order = $this->loadModel("Order");
		$this->set(array("queryorder"=>$order->QueryPrice()));
		$this->set(array("queryPrices"=>$order->queryPriceFromPackage()));
		$query = $order->QueryOrder("Package");
		$this->set(array("records"=>$order->DisplayAdminOrder($query,$this->get("page"),$this->get("perpage")?$this->get("perpage"):20,array("company_name"=>$this->get("search"),"Orders.status"=>$this->get("value_radio")),array("buy_date"),"ASC")));
		$this->set(array("getOrderByType"=>$order->GetOrderByType("Package")));
		$this->set("urls",$this->get("value_radio")?$this->get("value_radio"):"");
		$this->set("item",$this->get("search")?$this->get("search"):"");
		$this->set("perPage",$this->get("perpage")?$this->get("perpage"):20);
		$this->render("admin_display");
	}
	/*
	 * Author Phon Pisey
	* parameter: $addDay is for insert number of day that you 1 2 add
	* culDate: for calculate date
	*/
	public function culDate($addDay){
		$date = date("Y-m-d H:i:s");
		$date = strtotime($date);
		$date = strtotime("+" . $addDay . " day" , $date);
		$totalpointexpire = date('Y-m-d H:i:s', $date);
		return $totalpointexpire;
	}
	/*
	 * Author Phon Pisey
	* parameter: $addDay is for insert number of day that you 1 2 add
	* culDate: for calculate date
	*/
	public function culCutDate($addDay){
		if($addDay <= "0"){
			return 0;
		}else{
			$date = date("Y-m-d H:i:s");
			$date = strtotime($date);
			$date = strtotime("-" . $addDay . " day" , $date);
			$totalpointexpire = date('Y-m-d H:i:s', $date);
			return $totalpointexpire;
		}
	}
	public function approve_order_package(){
		$package= $this->loadModel("Package");
		$employer=$this->loadModel("Employer");
		$subscription = $this->loadModel("Subscription");
		$membership = $this->loadModel("Membership");
		$order = $this->loadModel("Order") ;
		$recordOrder =  $order->findAsObject(array("id="=>$this->get("order_id")));
		if($recordOrder->status == 0){
			$order->edit(array("status"=>1),array("id="=>$this->get("order_id")));
			/*select * from membership to compare to find data in database is NULL r not*/
			$valmembership = $membership->getData($recordOrder->emp_id,array("sub_type ="=>"Employer"));
			$valmembership = isset($valmembership->user_id)?$valmembership->user_id:NULL;
			/*query one row from database package that user check*/
			$findobjectpackage = $package->findAsObject(array("id="=>$recordOrder->item_id));
			$getpoint = intval($findobjectpackage->point);
			$getvalidday = intval($findobjectpackage->valid_day);
			/*get posting point from membership and keep it for addition*/
			$pointmembership = $membership->findAsObject(array("user_id ="=>$valmembership,"sub_type ="=>"Employer"));
			/*get emp_id from membership and keep it for comparation*/
			$empidmembership = $membership->findAsObject(array("user_id ="=>$valmembership,"sub_type ="=>"Employer"));
			/*get expire date from membership, calculate expire day of subscription and keep it for addition*/
			$valpointexpire = $membership->findAsObject(array("user_id ="=>$valmembership,"sub_type ="=>"Employer"));
			if(is_object($valpointexpire)){
				$now_date = date ("Y-m-d H:i:s");
				$leftpointexpire = (strtotime($valpointexpire->point_expire) - strtotime($now_date)) / (60 * 60 * 24);
			}else{
				$leftpointexpire = "";
			}
			/*check on left package expire*/
			if($leftpointexpire > 0){
				$leftpointexpire = ceil($leftpointexpire);
				$totalvaliddate = $leftpointexpire + $getvalidday;
				//Add left date with new date to field point_expire in table memberships
				$totalpointexpire = $this->culDate($totalvaliddate);
			}else{
				//Add new date to field point_expire in table memberships
				$totalpointexpire = $this->culDate($getvalidday);
			}
			$totalposting = $getpoint + (isset($pointmembership)?$pointmembership->posting_point:0) ;
			if(isset($empidmembership)?$empidmembership->user_id:NULL){
				$version = $membership->findAsObject(array("user_id="=>$valmembership,"sub_type ="=>"Employer"));
				$version = $version->version +1;
				$membership->EditMembership(array("posting_point"=>$totalposting,"point_expire"=>$totalpointexpire,"version"=>$version,"modify"=>date("Y-m-d H:i:s")),array("user_id="=>$recordOrder->emp_id));
			}else{
				$membership->save(array("user_id"=>$recordOrder->emp_id,"posting_point"=>$totalposting,"point_expire"=>$totalpointexpire,"created"=>date("Y-m-d H:i:s"),"sub_type"=>"Employer"));
			}
			//Alert mail to admin to tell that have an employer buy package
			$recordEmp = $employer->findObject(array("id = "=>$recordOrder->emp_id));
			$str = "Dear " .$recordEmp->firstname ." ".$recordEmp->lastname ."<br/><br/>";
			$str .= "Here is your package that you bought:<br/>";
			$str .= "Package's Name : " .$findobjectpackage->title."<br/>";
			$str .= "Price : " .$findobjectpackage->price." $<br/>";
			$str .= "Point : " .$findobjectpackage->point."<br/>";
			$str .= "Valid Day : " .$findobjectpackage->valid_day." Days<br/>";
			$subject ="HRCambodia .com Alert Comfirm Order Package";
			$msgHTML = "Your Package Has Approved From Our Company";
			$this->sendMail($str,$subject,$msgHTML,$recordEmp->email);
		}
		//Render back to display admin after approve
		$this->DisplayAdminPackageOrder();
	}
	public function disapprove_order_package(){
		/* Add point to membership who has approve from super admin */
		$package= $this->loadModel("Package");
		$employer=$this->loadModel("Employer");
		$subscription = $this->loadModel("Subscription");
		$order = $this->loadModel("Order");
		$recordOrder =  $order->findAsObject(array("id="=>$this->get("order_id")));
		/*Get one record from table order*/
		$order->edit(array("status"=>2),array("id="=>$this->get("order_id")));
		//Alert mail to admin to tell that have an employer buy package
		$recordEmp = $employer->findObject(array("id = "=>$recordOrder->emp_id));
		$str = "Dear " .$recordEmp->firstname ." ".$recordEmp->lastname ."<br/><br/>";
		$str .= "Your package hasn't been approved from our company:<br/>";
		$str .= "Package's Name : " .$recordOrder->item."<br/>";
		$str .= "Price : " .$recordOrder->amount." $<br/>";
		$str .= "Point : " .$recordOrder->point."<br/>";
		$str .= "Valid Day : " .$recordOrder->valid_day." Days<br/>";
		$subject ="HRCambodia .com Alert Not Comfirm Order Package";
		$msgHTML = "Your Package Hasn't Approved From Our Company";
		$this->sendMail($str,$subject,$msgHTML,$recordEmp->email);
		//Render back to display admin after disapprove
		$this->DisplayAdminPackageOrder();
	}
	public function showSearch(){
		$order = $this->loadModel("Order");
		$this->set(array("queryorder"=>$order->QueryPrice()));
		$this->set(array("queryPrices"=>$order->queryPriceFromPackage()));
		$query = $order->QueryOrder("Package");
		$this->set(array("records"=>$order->AdminOrder($query,$this->get("page"),$this->get("perpage")?$this->get("perpage"):20,$this->get("value_radio"),array("Orders.status"),array("buy_date"),"ASC")));
		$this->set(array("getOrderByType"=>$order->GetOrderByType("Package")));
		$this->set("urls",$this->get("value_radio")?$this->get("value_radio"):"");
		$this->render("admin_display");
	}
	/**
	 * Author Phon Pisey
	 * @param unknown_type $str (string to show in content)
	 * @param unknown_type $subject (subject of email)
	 * @param unknown_type $msgHTML (String in head content)
	 * @param unknown_type $email (email address send to)
	 * Function for sending mail to an address email
	 */
	public function sendMail($str,$subject,$msgHTML,$email){
		ob_start();
		//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
		Import::util('class.phpmailer');
		//the true param means it will throw exceptions on errors, which we need to catch
		$mail = new PHPMailer(true);
		//telling the class to use SMTP
		$mail->IsSMTP();
		try {
			// SMTP server
			$mail->Host = "mail.atmos-techno.com";
			// enables SMTP debug information (for testing),  show debug : SMTPDebug  = 2,  Hide debug : SMTPDebug  = 1
			$mail->SMTPDebug = 1;
			// enable SMTP authentication
			$mail->SMTPAuth = true;
			// sets the SMTP server
			$mail->Host = "mail.atmos-techno.com";
			// set the SMTP port for the MY OWN DOMAIN server
			$mail->Port = 26;
			// SMTP account username
			$mail->Username = "demo@atmos-techno.com";
			// SMTP account password
			$mail->Password = "demo*123456";
			//$mail->AddAddress('phonpisey23@gmail.com','');
			$email_address = filter_input(INPUT_GET, $email, FILTER_VALIDATE_EMAIL);
			if (!$email_address) {
				$mail->SetFrom('demo@atmos-techno.com', 'HRCambodia');
				// $mail->AddAddress('info@atmos-techno.com', 'Atmosphere Technology Co.,Ltd');
				$mail->AddAddress($email, $email);
				//$mail->AddAddress('phonpisey23@gmail.com','');
				$mail->AddReplyTo('demo@atmos-techno.com', 'sales@hrcambodia.com');
				$mail->Subject = $subject;
				// optional - MsgHTML will create an alternate automatically
				$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
				$mail->MsgHTML("<h3>" . $msgHTML." </h3>" . $str . "<br/>");
				$mail->Send();
			} else {
				//echo 'Email is invalid...';
				break;
			}
		} catch (phpmailerException $e) {
			//Pretty error messages from PHPMailer
			echo $e->errorMessage();
		} catch (Exception $e) {
			//Boring error messages from anything else!
			echo $e->getMessage();
		}
	}
	public function DisplayAdminSubscriptionOrder(){
		$order = $this->loadModel("Order");
		$this->set(array("queryorder"=>$order->QueryPrice()));
		$this->set(array("queryPrices"=>$order->queryPriceFromPackage()));
		$query = $order->QueryOrder("Subscription");
		$this->set(array("records"=>$order->DisplayAdminOrder($query,$this->get("page"),$this->get("perpage")?$this->get("perpage"):20,array("company_name"=>$this->get("search"),"Orders.status"=>$this->get("value_radio")),array("buy_date"),"ASC")));
		$this->set(array("getOrderByType"=>$order->GetOrderByType("Package")));
		$this->set("urls",$this->get("value_radio")?$this->get("value_radio"):"");
		$this->set("item",$this->get("search")?$this->get("search"):"");
		$this->set("perPage",$this->get("perpage")?$this->get("perpage"):20);
		$this->render("admin_subscription_order");
	}
	public function approve_order_sub(){
		$subscription= $this->loadModel("Subscription");
		$order= $this->loadModel("Order");
		$membership = $this->loadModel("Membership");
		$employer = $this->loadModel("Employer");		
		$checkedbox = $this->get("order_id");
		/*Get one record from table order*/
		$recordOrder = $order->findAsObject(array("id="=>$checkedbox));
		// if this rocord already approve , won't approve and add point again
		if($recordOrder->status != "1"){
			//update on status in order
			$getDataUpdate = $order->edit(array("status"=>1),array("id="=>$checkedbox));
			/*query one row from database package that user check*/
			$findobjectsubscription = $subscription->findAsObject(array("id="=>$getDataUpdate->item_id));
			$getvalidday = intval($findobjectsubscription->duration);
			/*get emp_id from membership and keep it for comparation*/
			$empidmembership = $membership->findAsObject(array("user_id="=>$getDataUpdate->emp_id,"sub_type ="=>"Employer"));
			$totalsubscriptionexpire = $this->culDate($getvalidday);
			if($empidmembership){
				$version = $membership->findAsObject(array("user_id="=>$getDataUpdate->emp_id,"sub_type ="=>"Employer"));
				$version = $version->version +1;
				$membership->EditMembership(array("subscription_start"=>date("Y-m-d H:i:s"),"subscription_expire"=>$totalsubscriptionexpire,"version"=>$version,"modify"=>date("Y-m-d H:i:s")),array("user_id="=>$recordOrder->emp_id));
			}else{
				$membership->InsertMembership($recordOrder->emp_id,$findobjectsubscription);
			}
			//Alert mail to admin to tell that have an employer buy package
			$recordEmp = $employer->findObject(array("id = "=>$getDataUpdate->emp_id));
			$str = "Dear " .$recordEmp->firstname ." ".$recordEmp->lastname ."<br/><br/>";
			$str .= "You have bought a subscription:<br/>";
			$str .= "Subscription's Name : " .$findobjectsubscription->title."<br/>";
			$str .= "Price : " .$findobjectsubscription->price." $<br/>";
			$str .= "Valid Day : " .$findobjectsubscription->duration." Days<br/>";
			$subject ="HRCambodia .com Alert Comfirm Order Subscription";
			$msgHTML = "Your Subscription Package Has Approved From Our Company";
			$this->sendMail($str,$subject,$msgHTML,$recordEmp->email);
		}
		$this->DisplayAdminSubscriptionOrder();
	}
	public function disapprove_order_sub(){
		$subscription= $this->loadModel("Subscription");
		$order= $this->loadModel("Order");
		$membership = $this->loadModel("Membership");
		$employer = $this->loadModel("Employer");
		$checkedbox = $this->get("order_id");
		/*Get one record from table order*/
		$recordOrder = $order->findAsObject(array("id="=>$checkedbox));
		// if this rocord already approve , won't approve and add point again
		if($recordOrder->status != "2"){
			$getDataUpdate = $order->edit(array("status"=>2),array("id="=>$checkedbox));
			//Alert mail to admin to tell that have an employer buy package
			$recordEmp = $employer->findObject(array("id = "=>$getDataUpdate->emp_id));
			$str = "Dear " .$recordEmp->firstname ." ".$recordEmp->lastname ."<br/><br/>";
			$str .= "Here is the subscription package that you bought:<br/>";
			$str .= "Subscription's Name : " .$recordOrder->item."<br/>";
			$str .= "Price : " .$recordOrder->amount." $<br/>";
			$str .= "Valid Day : " .$recordOrder->valid_day." Days<br/>";
			$subject ="HRCambodia .com Alert Not Comfirm Order Subscription";
			$msgHTML = "Your Subscription Package Hasn't Approved From Our Company";
			$this->sendMail($str,$subject,$msgHTML,$recordEmp->email);
		}
		$this->DisplayAdminSubscriptionOrder();
	}
	/**
	 * Author Phon Pisey
	 * @param unknown_type $dds (id of record when user click to delete or disapprove)
	 * Function for cut data with Subscription when disapprove and delete order
	 */
	public function cutDataWhenAppAndDeletePack($dds){
		/* Add point to membership who has approve from super admin */
		$package= $this->loadModel("Package");
		$order= $this->loadModel("Order");
		$membership= $this->loadModel("Membership");
		//find in table order
		$recordOrder = $order->findAsObject(array("id="=>$dds));
		/*query one row from database package that user check*/
		$findobjectpackage = $package->findAsObject(array("id="=>$recordOrder->item_id));
		$getpoint = intval($findobjectpackage->point);
		$getvalidday = intval($findobjectpackage->valid_day);
		/*get posting point from membership and keep it for addition*/
		$pointmembership = $membership->findAsObject(array("user_id ="=>$recordOrder->emp_id,"sub_type ="=>"Employer"));
		/*get emp_id from membership and keep it for comparation*/
		$empidmembership = $membership->findAsObject(array("user_id ="=>$recordOrder->emp_id,"sub_type ="=>"Employer"));
		/*get expire date from membership, calculate expire day of subscription and keep it for addition*/
		$valpointexpire = $membership->findAsObject(array("user_id ="=>$recordOrder->emp_id,"sub_type ="=>"Employer"));
		if(is_object($valpointexpire)){
			$now_date = date ("Y-m-d H:i:s");
			$leftpointexpire = (strtotime($valpointexpire->point_expire) - strtotime($now_date)) / (60 * 60 * 24);
		}else{
			$leftpointexpire="";
		}
		if($pointmembership){
			$totalposting = $pointmembership->posting_point - $getpoint;
		}else{
			$totalposting = "";
		}
		/*check on left subscription expire*/
		if($leftpointexpire > 0){
			$leftpointexpire = ceil($leftpointexpire);
			$totalvaliddate = $leftpointexpire - $getvalidday;
			//Add left date with new date to field point_expire in table memberships
			$totalpointexpire = $this->culCutDate($totalvaliddate);
		}
		if($empidmembership){
			$version = $membership->findAsObject(array("user_id="=>$recordOrder->emp_id,"sub_type ="=>"Employer"));
			$version = $version->version +1;
			$membership->EditMembership(array("posting_point"=>$totalposting,"point_expire"=>$totalpointexpire,"version"=>$version,"modify"=>date("Y-m-d H:i:s")),array("user_id="=>$this->emp_session["id"]));
		}else{
			$membership->save(array("user_id"=>$this->emp_session["id"],"posting_point"=>$totalposting,"point_expire"=>$totalpointexpire,"created"=>date("Y-m-d H:i:s"),"sub_type"=>"Employer"));
		}
	}
	/**
	 * Author Phon Pisey
	 * @param unknown_type $dds (id of record when user click to delete or disapprove)
	 * Function for cut data with Package when disapprove and delete order
	 */
	public function cutDataWhenAppAndDeleteSub($dds){
		$subscription = $this->loadModel("Subscription");
		$order= $this->loadModel("Order");
		$membership = $this->loadModel("Membership");
		//find in table order
		$getDataUpdate = $order->findAsObject(array("id="=>$dds));
		/*query one row from database package that user check*/
		$findobjectsubscription = $subscription->findAsObject(array("id="=>$getDataUpdate->item_id));
		$getvalidday = intval($findobjectsubscription->duration);
		/*get emp_id from membership and keep it for comparation*/
		$empidmembership = $membership->findAsObject(array("user_id="=>$getDataUpdate->emp_id,"sub_type ="=>"Employer"));
		/*get expire date from membership, calculate expire day of subscription and keep it for addition*/
		$valsubscriptionexpire = $membership->findAsObject(array("user_id="=>$getDataUpdate->emp_id,"sub_type ="=>"Employer"));
		if($valsubscriptionexpire){
			$now_date = date ("Y-m-d H:i:s");
			$leftsupscriptionexpire = (strtotime($valsubscriptionexpire->subscription_expire) - strtotime($now_date)) / (60 * 60 * 24);
		}else{
			$leftsupscriptionexpire = "";
		}
		/*check on left subscription expire*/
		$totalsubscriptionexpire = "";
		if($leftsupscriptionexpire > 0){
			$leftsupscriptionexpire = ceil($leftsupscriptionexpire);
			$totalvaliddate = $leftsupscriptionexpire - $getvalidday;
			//Add left date with new date to field subscription_expire
			$totalsubscriptionexpire = $this->culCutDate($totalvaliddate);
		}
		if($empidmembership){
			$version = $membership->findAsObject(array("user_id="=>$getDataUpdate->emp_id,"sub_type ="=>"Employer"));
			$version = $version->version +1;
			$membership->EditMembership(array("subscription_expire"=>$totalsubscriptionexpire,"subscription_start"=>NULL,"version"=>$version,"modify"=>date("Y-m-d H:i:s")),array("user_id="=>$this->emp_session["id"]));
		}else{
			$membership->InsertMembership($this->emp_session["id"],$findobjectsubscription);
		}
	}
	public function DisplayAdminPostOrder(){
		$this->render("admin_posting_order");
	}
}
